﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace test
{
    public partial class Form1 : Form
    {
        bool wait=true;
        string std;
        public delegate void outdelegate(string result);
        public delegate void errdelegate(string result);
        public event outdelegate outevent;
        public event errdelegate errevent;
        void CMDoperator3(string cmd)
        {
            Process p_cmd = new Process();//新建对向
            p_cmd.StartInfo.FileName = "cmd.exe";//打开的软件名称
            p_cmd.StartInfo.UseShellExecute = false;//禁止使用用户shell
            p_cmd.StartInfo.CreateNoWindow = true;//创建没有窗体

            p_cmd.StartInfo.RedirectStandardInput = true;//输入重定向
            p_cmd.StartInfo.RedirectStandardOutput = true;//输出重定向
            p_cmd.StartInfo.RedirectStandardError = true;//报错重定向

            //注册两个事件+=,取消注册事件使用-=
            p_cmd.OutputDataReceived += new DataReceivedEventHandler(outtext);
            p_cmd.ErrorDataReceived += new DataReceivedEventHandler(errtext);


            p_cmd.Start();//启动
            p_cmd.BeginErrorReadLine();//异步读取err
            p_cmd.BeginOutputReadLine();//异步读取output
            p_cmd.StandardInput.AutoFlush = true;//自动推送，不存缓存
            p_cmd.StandardInput.WriteLine(cmd + "&exit");//写入命令
            //p_cmd.WaitForExit();
        }
        void CMDoperator(string cmd, System.Text.Encoding errencoding,System.Text.Encoding outputencoding,bool wait)
        {
            Process p_cmd = new Process();//新建对向
            p_cmd.StartInfo.FileName = "cmd.exe";//打开的软件名称
            p_cmd.StartInfo.UseShellExecute = false;//禁止使用用户shell
            p_cmd.StartInfo.CreateNoWindow = true;//创建没有窗体

            p_cmd.StartInfo.RedirectStandardInput = true;//输入重定向
            p_cmd.StartInfo.RedirectStandardOutput = true;//输出重定向
            p_cmd.StartInfo.RedirectStandardError = true;//报错重定向

            p_cmd.StartInfo.StandardErrorEncoding = errencoding;//定义错误流的编码格式防止乱码
            p_cmd.StartInfo.StandardOutputEncoding = outputencoding;//定义输出流的编码格式防止乱码

            //注册两个事件
            //outevent += new outdelegate(outtext);
            //errevent += new errdelegate(errtext);

            //注册两个事件+=,取消注册事件使用-=
            p_cmd.OutputDataReceived += new DataReceivedEventHandler(outreceived);
            p_cmd.ErrorDataReceived += new DataReceivedEventHandler(errreceived);


            p_cmd.Start();//启动
            p_cmd.BeginErrorReadLine();//异步读取err
            p_cmd.BeginOutputReadLine();//异步读取output
            p_cmd.StandardInput.AutoFlush = true;//自动推送，不存缓存
            p_cmd.StandardInput.WriteLine(cmd + "&exit");//写入命令
            if (wait) p_cmd.WaitForExit();


        }
        string CMDoperator1(string cmd)
        {
            Process p_cmd = new Process();//新建对向
            p_cmd.StartInfo.FileName = "cmd.exe";//打开的软件名称
            p_cmd.StartInfo.UseShellExecute = false;//禁止使用用户shell
            p_cmd.StartInfo.CreateNoWindow = true;//创建没有窗体

            p_cmd.StartInfo.RedirectStandardInput = true;//输入重定向
            p_cmd.StartInfo.RedirectStandardOutput = true;//输出重定向
            p_cmd.StartInfo.RedirectStandardError = true;//报错重定向

            p_cmd.Start();//启动
            p_cmd.StandardInput.AutoFlush = true;//自动推送，不存缓存
            p_cmd.StandardInput.WriteLine(cmd + "&exit");//写入命令
            p_cmd.WaitForExit();
            string ao="", ae="",aa="";
            while(!p_cmd.StandardError.EndOfStream)
            {
                ae = p_cmd.StandardError.ReadLine();
            }
            while (!p_cmd.StandardOutput.EndOfStream)
            {
                ao = p_cmd.StandardOutput.ReadLine();
            }
            if (ae == "")
            {
                aa = ao;
            }
            else
            {
                aa =ae;
            }
            p_cmd.Dispose();
            return aa;

        }
        void outtext(object sender, System.Diagnostics.DataReceivedEventArgs e)
        {
            if(e.Data!=null)
            this.BeginInvoke(new Action(() =>
            {
                richTextBox2.AppendText(e.Data + "\r\n");
                richTextBox2.SelectionStart = richTextBox2.TextLength;
                richTextBox2.ScrollToCaret();
            }));
        }
        void errtext(object sender, System.Diagnostics.DataReceivedEventArgs e)
        {
            if(e.Data!=null)
                this.BeginInvoke(new Action(() =>
            {
                richTextBox2.AppendText(e.Data + "\r\n");
                richTextBox2.SelectionStart = richTextBox2.TextLength;
                richTextBox2.ScrollToCaret();
            }));
        }
        void outreceived(object sender, System.Diagnostics.DataReceivedEventArgs e)
        {
            if (e.Data != null)
            {
                //outevent(e.Data);
                this.BeginInvoke(new Action(() =>
                {
                    if (richTextBox1.TextLength >= 10000) richTextBox1.Clear();
                    richTextBox1.AppendText(e.Data + "\r\n"); 
                    richTextBox1.SelectionStart = richTextBox1.TextLength;
                    richTextBox1.ScrollToCaret();
                    if (e.Data.Contains(@" connected"))
                    {
                        toolStripStatusLabel2.Text = "共享已启动";
                        toolStripStatusLabel2.BackColor = System.Drawing.Color.Green;
                        wait = false;
                        CMDoperator(std + @"./adb shell svc data disable", Encoding.UTF8, Encoding.Default, true);
                    }
                    if (e.Data.Contains(@" disconnected"))
                    {
                        toolStripStatusLabel2.Text = "共享未启动";
                        toolStripStatusLabel2.BackColor = System.Drawing.Color.Red;
                        wait = true;
                    }
                }));
                // 4. 异步调用，需要invoke
                //this.Invoke(outevent, new object[] { e.Data });
                //Console.WriteLine(e.Data);
            }
        }
        void errreceived(object sender, System.Diagnostics.DataReceivedEventArgs e)
        {
            if (e.Data != null)
            {
                
                this.BeginInvoke(new Action(() =>
                {
                    if (richTextBox1.TextLength >= 10000) richTextBox1.Clear();
                    richTextBox1.AppendText(e.Data + "\r\n");
                    richTextBox1.SelectionStart = richTextBox1.TextLength;
                    richTextBox1.ScrollToCaret();
                }));
                // 4. 异步调用，需要invoke
                //this.Invoke(errevent, new object[] { e.Data });
                //Console.WriteLine(e.Data);
            }

        }
        public Form1()
        {
            InitializeComponent(); 
            //激活窗体并给予它焦点 
            this.Activate();
            std = Application.StartupPath;//启动文件地址赋值
        }

        private void button1_Click(object sender, EventArgs e)
        {
                //CMDoperator1(std + @"./gnirehtet stop");
                //CMDoperator1(@"TASKKILL /T /F /IM gnirehtet.exe");
                CMDoperator(std + @"./gnirehtet autorun", Encoding.UTF8, Encoding.Default, false);
           
        }

        private void button2_Click(object sender, EventArgs e)
        {
            CMDoperator3(std + @"./gnirehtet stop");
            CMDoperator3(std + @"./adb shell svc data enable");
            CMDoperator3(@"TASKKILL /T /F /IM gnirehtet.exe");
        }

        private void notifyIcon1_MouseClick(object sender, MouseEventArgs e)
        {
            //判断是否已经最小化于托盘 
            if (WindowState == FormWindowState.Minimized)
            {
                //Show();
                //还原窗体显示 
                WindowState = FormWindowState.Normal;
                //激活窗体并给予它焦点 
                this.Activate();
                //任务栏区显示图标 
                this.ShowInTaskbar = true;
                //托盘区图标隐藏 
                //notifyIcon1.Visible = false;
            }
        }

        private void Form1_MinimumSizeChanged(object sender, EventArgs e)
        {
        }

        private void Form1_SizeChanged(object sender, EventArgs e)
        {
            //判断是否选择的是最小化按钮 
            if (WindowState == FormWindowState.Minimized)
            {
                //Hide();
                //托盘显示图标等于托盘图标对象 
                //注意notifyIcon1是控件的名字而不是对象的名字 
                //notifyIcon1.Icon = ico;
                //隐藏任务栏区图标 
                this.ShowInTaskbar = false;
                //图标显示在托盘区 
                //notifyIcon1.Visible = true;
            }

        }

        private void Form1_FormClosed(object sender, FormClosedEventArgs e)
        {
            notifyIcon1.Dispose();
            button2_Click(sender, e);
            CMDoperator3(@"TASKKILL /T /F /IM adb.exe");
            Environment.Exit(0);
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            //Thread status = new Thread(() => { while (true) { CMDoperator(std + @"./adb get-state", Encoding.Default, Encoding.Default, true); Thread.Sleep(500); this.BeginInvoke(new Action(() => { toolStripStatusLabel1.Text=""; })); } });
            Thread status = new Thread(new ThreadStart(te));
            status.Start();
        }

        private void tableLayoutPanel1_Paint(object sender, PaintEventArgs e)
        {

        }

        private void button3_Click(object sender, EventArgs e)
        {
            CMDoperator3(std + @"./adb install -r gnirehtet.apk");
        }
        void te()
        {
            string st;
            while (true)
            {
                st = CMDoperator1(std + @"./adb get-state");
                Invoke(new Action(() =>
                {
                    //sleep不能够放在这里面不然会造成ui卡顿
                    if (st == "device")
                    {
                        toolStripStatusLabel1.BackColor = Color.Green;
                        toolStripStatusLabel1.Text = "设备已连接";
                    }
                    else
                    {
                        toolStripStatusLabel1.BackColor = Color.Red;
                        toolStripStatusLabel1.Text = "设备未连接";
                    }
                    if (toolStripStatusLabel1.Text == "设备已连接")
                    {
                        button1.Enabled = button2.Enabled = button3.Enabled = true;
                    }
                    else
                    {
                        button1.Enabled = button2.Enabled = button3.Enabled = false;
                    }
                }));
                Thread.Sleep(500);
            }
        }
        void te1()
        {
            while (true)
            {
                Thread.Sleep(1000);
            }
        }
        protected override void WndProc(ref System.Windows.Forms.Message m)
        {
            switch (m.Msg)
            {
                case 0x11:
                    if ((m.LParam.ToInt32() == 1073741824) || (m.LParam.ToInt32() == -2147483648) )//重启关机,注销
                    {
                        Environment.Exit(0);
                    }
                    break;
            }
            //监控：拦截窗体最小化按钮消息 
            //if (m.Msg == 0x0112)
            //{
            //    if (m.WParam.ToInt32() == 0xF020)
            //    {
            //        using (StreamWriter a = new StreamWriter("x.txt"))
            //        {
            //            a.WriteLine(m.Msg.ToString());
            //            a.WriteLine(m.WParam.ToString());
            //            a.WriteLine(m.LParam.ToString());
            //        }
            //        //制定自己处理
            //        //MessageBox.Show("wo");
            //        //return;//阻止最小化
            //    }
            //}

            //执行默认消息
            base.WndProc(ref m);
        }

    }
}
